package cn.tedu.myboot29.controller;

import cn.tedu.myboot29.entity.User;
import cn.tedu.myboot29.entity.Weibo;
import cn.tedu.myboot29.mapper.WeiboMapper;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;


import java.util.Date;
import java.util.List;
import java.util.UUID;

@RestController
public class WeiboController {
    @Autowired(required = false)
    WeiboMapper mapper;
    @RequestMapping("/send")
    public int send(Weibo weibo, MultipartFile picFile, HttpSession session) throws IOException {
        User user= (User) session.getAttribute("user");
        if (user!=null){
            return 2;
        }
        String fileName=picFile.getOriginalFilename();
        String suffix=fileName.substring(fileName.lastIndexOf("."));
        fileName= UUID.randomUUID()+suffix;
        String dirPath="E:/upload/";
        File dirFile=new File(dirPath);
        if (!dirFile.exists()){
            dirFile.mkdirs();
        }
        String filePath=dirPath+fileName;
        picFile.transferTo(new File(filePath));
        weibo.setAuthor(user.getNick());
        weibo.setCreated(new Date());
        weibo.setUserId(user.getId());
        weibo.setUrl("/"+fileName);
        mapper.insert(weibo);
        return 1;
    }
    @RequestMapping("/select")
    public List<Weibo> select(){
        return mapper.select();
    }

}
